import json

import requests
from PyQt5.QtCore import QObject, pyqtSlot, pyqtSignal

from cache import Cache
from dao.commonDao import CommonDao
from protoc.noticeType import NoticeType


class AddFriendAction(QObject):

    def __init__(self):
        super().__init__()


    @pyqtSlot(int, result=str)
    def searchFriend(self,userId):
        try:
            header = {'clientOs': '1', 'token':Cache.userInfo['token'], 'id':str(Cache.userInfo['id'])}
            url = 'http://localhost:8080/walala-api/user/search?userId=' + str(userId)
            r = requests.get(url,headers=header)
            if r.status_code == 200:
                return r.text
            else:
                return None
        except Exception as e:
            print(e)

    @pyqtSlot(int,result=int)
    def checkIsFriend(self,userId):
        result = Cache.dao.getFriendByUserId(userId)
        if result is not None:
            return 0
        else:
            return 1

    @pyqtSlot(int,str,result=str)
    def add(self,userId,extra):
        try:
            header = {'clientOs': '1', 'token': Cache.userInfo['token'], 'id': str(Cache.userInfo['id'])}
            url = 'http://localhost:8080/walala-api/friend/apply'
            extra_ = {'extra':extra,'status':2,'type':NoticeType.addFriend}
            extraStr = json.dumps(extra_)
            param = {'senderId':Cache.userInfo['id'],'receiverId':userId,'senderName':Cache.userInfo['username'],'extra':extraStr}

            print(param)
            r = requests.post(url, json=param,headers=header)
            if r.status_code == 200:
                result = json.loads(r.text)
                if result['code'] == 0:
                    if result['data'] == True:
                        url = 'http://localhost:8080/walala-api/message/notify'
                        text = Cache.userInfo['username'] + '请求添加你为好友'
                        param = {'senderId':Cache.userInfo['id'],'msgBody': text, 'receiverId': userId, 'senderName': Cache.userInfo['username'],'notifyType':1,
                                 'extra': extraStr,'msgType':1}
                        print(param)
                        r = requests.post(url, json=param, headers=header)
                        if r.status_code == 200:
                            result = json.loads(r.text)
                            if result['code'] == 0:
                                return '已发送，请等待对方通过'
                            else:
                                return '申请失败，请稍后再试'
                    else:
                        return result['msg']
                else:
                    return result['msg']
            else:
                return None
        except Exception as e:
            print(e)


